﻿using FreeSql.Internal.ObjectPool;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using PropertyManagementSystemAPI.Models;
using System.Data.Common;

namespace PropertyManagementSystemAPI.Controllers
{
    /// <summary>
    /// 业主信息管理
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    [EnableCors("any")]
    [Authorize]
    public class OwnerInfoController : ControllerBase
    {
        IFreeSql db;
        public OwnerInfoController(IFreeSql _db)
        {
            db = _db;
        }

        /// <summary>
        /// 查询全部数据
        /// </summary>
        /// <param name="page">页数</param>
        /// <param name="limit">条数</param>
        /// <param name="hnumber">房产编号</param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetInfo(int page, int limit, string? hnumber)
        {
            var list = db.Select<Models.Ownerinfo, Models.Houseinfo>()
                .LeftJoin((a, b) => a.Hid == b.Hid)
                .Where((a, b) => ((string.IsNullOrEmpty(hnumber)) || (b.Hnumber.Contains(hnumber))) && (a.Isdelete != true))
                .Count(out var total)
                .Page(page, limit)
                .ToList((a, b) => new
                {
                    a.Oid,
                    a.Ologincode,
                    b.Hid,
                    b.Hnumber,
                    b.Hname,
                    a.Orealname,
                    a.Osex,
                    a.Oimg,
                    a.Oidcard,
                    a.Ophone,
                    a.Obirthday,
                    a.Createtime
                });
            var json = new
            {
                data = list,
                total = total,
                code = 200
            };
            return Ok(json);
        }


        /// <summary>
        /// 添加业主信息
        /// </summary>
        /// <param name="info">实体类</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<bool> Add([FromBody] Models.Ownerinfo info)
        {
            using Object<DbConnection> conn = db.Ado.MasterPool.Get();
            using DbTransaction transaction = conn.Value.BeginTransaction();
            bool res = false;
            try
            {
                info.Createtime = DateTime.Now;
                info.Isdelete = false;
                await db.Insert(info)
                    .WithTransaction(transaction)
                    .ExecuteAffrowsAsync();

                await db.Update<Models.Houseinfo>(info.Hid)
                    .Set(x => x.Hstate == 1)
                    .WithTransaction(transaction)
                    .ExecuteAffrowsAsync();
                res = true;
                transaction.Commit();
            }
            catch (Exception ex)
            {
                transaction.Rollback();
                res = false;
            }
            return res;
        }

        /// <summary>
        /// 编辑业主信息
        /// </summary>
        /// <param name="ownerinfo"></param>
        /// <returns></returns>
        [HttpPut]
        public bool Edit(Models.Ownerinfo info)
        {
            bool res = false;
            try
            {
                info.Isdelete = false;
                db.Update<Ownerinfo>(info.Oid)
                .Set(a => a.Oidcard == info.Oidcard)
                .Set(a => a.Oimg == info.Oimg)
                .Set(a => a.Obirthday == info.Obirthday)
                .Set(a => a.Orealname == info.Orealname)
                .Set(a => a.Osex == info.Osex)
                .Set(a => a.Ologincode == info.Ologincode)
                .Set(a => a.Ophone == info.Ophone)
                .ExecuteAffrows();
                res = true;
            }
            catch (Exception ex)
            {
                res = false;
            }
            return res;
        }

        /// <summary>
        /// 删除/多选删除
        /// </summary>
        /// <param name="oid">业主信息ID</param>
        /// <param name="hid">房产ID</param>
        /// <returns></returns>
        [HttpDelete]
        public async Task<bool> Del(string oid, string hid)
        {
            int[] into = new int[oid.Split(',').Length];
            for (int i = 0; i < oid.Split(',').Length; i++)
            {
                into[i] = int.Parse(oid.Split(",")[i]);
            }

            int[] inth = new int[hid.Split(',').Length];
            for (int i = 0; i < hid.Split(',').Length; i++)
            {
                inth[i] = int.Parse(hid.Split(",")[i]);
            }

            using Object<DbConnection> conn = db.Ado.MasterPool.Get();
            using DbTransaction transaction = conn.Value.BeginTransaction();
            bool res = false;
            try
            {
                await db.Update<Models.Ownerinfo>(into)
                    .Set(x => x.Isdelete == true)
                    .WithTransaction(transaction)
                    .ExecuteAffrowsAsync();

                await db.Update<Models.Houseinfo>(inth)
                    .Set(x => x.Hstate == 0)
                    .WithTransaction(transaction)
                    .ExecuteAffrowsAsync();
                res = true;

                transaction.Commit();
            }
            catch (Exception ex)
            {
                transaction.Rollback();
                res = false;
            }
            return res;
        }

        /// <summary>
        /// 获取业主信息绑定下拉框
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Route("getOwnerInfoBindSelect")]
        public ActionResult getOwnerInfoBindSelect()
        {
            var list = db.Select<Models.Ownerinfo>().Where(a => a.Isdelete == false).ToList(a => new
            {
                a.Oid,
                a.Orealname
            });
            return Ok(list);
        }
    }
}
